package com.jse;

import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import com.jse.util.Cookies;
import com.jse.util.Json;

@SuppressWarnings("deprecation")
public class JseSession implements HttpSession {

	private HttpSession sess;

	public JseSession(HttpServletRequest req, HttpServletResponse resp) {
		sess = req.getSession(false);
		if (sess == null) {
			sess = req.getSession();
			Map<String, String> m = Cookies.getCookie(req, resp);
			m.forEach((k, v) -> {
				if(sess.getAttribute(k)==null) {
					try {
						sess.setAttribute(k, Json.fromJson(URLDecoder.decode(v, "utf-8")));
					} catch (Exception e) {
						sess.setAttribute(k, v);
					}	
				}
			});
		}
	}

	@Override
	public Object getAttribute(String key) {
		return sess.getAttribute(key);
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		return sess.getAttributeNames();
	}

	@Override
	public long getCreationTime() {
		return sess.getCreationTime();
	}

	@Override
	public String getId() {
		return sess.getId();
	}

	@Override
	public long getLastAccessedTime() {
		return sess.getLastAccessedTime();
	}

	@Override
	public int getMaxInactiveInterval() {
		return sess.getMaxInactiveInterval();
	}

	@Override
	public ServletContext getServletContext() {
		return sess.getServletContext();
	}

	@Override
	public HttpSessionContext getSessionContext() {
		return sess.getSessionContext();
	}

	@Override
	public Object getValue(String key) {
		return sess.getValue(key);
	}

	@Override
	public String[] getValueNames() {
		return sess.getValueNames();
	}

	@Override
	public void invalidate() {
		sess.invalidate();
	}

	@Override
	public boolean isNew() {
		return sess.isNew();
	}

	@Override
	public void putValue(String key, Object obj) {
		sess.putValue(key, obj);
	}

	@Override
	public void removeAttribute(String key) {
		sess.removeAttribute(key);
	}

	@Override
	public void removeValue(String val) {
		sess.removeAttribute(val);
	}

	@Override
	public void setAttribute(String name, Object val) {
		sess.setAttribute(name, val);
	}

	@Override
	public void setMaxInactiveInterval(int val) {
		sess.setMaxInactiveInterval(val);
	}

	public Object get(String key) {
		return getAttribute(key);
	}

	public void put(String name, Object val) {
		setAttribute(name, val);
	}
	
	public void set(String name, Object val) {
		setAttribute(name, val);
	}
	
	public void put(String name, Object val, String path) {
		setAttribute(name, val);
	}

	public void close() {
		invalidate();
	}

}
